package com.trace.demo.controller;

import com.trace.demo.entity.TodoTask;
import com.trace.demo.entity.User;
import com.trace.demo.repository.TodoTaskRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 待办任务控制器
 */
@RestController
@RequestMapping("/api/todo-tasks")
public class TodoTaskController {

    @Autowired
    private TodoTaskRepository todoTaskRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 获取所有待办任务（分页）
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllTodoTasks(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Boolean completed,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) String[] dateRange) {
        
        try {
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("dueDate").ascending());
            
            Page<TodoTask> page;
            
            if (userId != null && completed != null) {
                page = todoTaskRepository.findByUserIdAndCompleted(userId, completed, pageable);
            } else if (userId != null) {
                page = todoTaskRepository.findByUserId(userId, pageable);
            } else {
                page = todoTaskRepository.findAll(pageable);
            }
            
            // 转换为Map格式
            List<Map<String, Object>> content = page.getContent().stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
            
            // 创建分页响应
            Map<String, Object> response = new HashMap<>();
            response.put("content", content);
            response.put("totalElements", page.getTotalElements());
            response.put("totalPages", page.getTotalPages());
            response.put("size", page.getSize());
            response.put("number", page.getNumber());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取待办任务列表成功", response));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取待办任务列表失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 获取单个待办任务
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTodoTaskById(@PathVariable Long id) {
        try {
            Optional<TodoTask> todoTaskOpt = todoTaskRepository.findById(id);
            if (!todoTaskOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "待办任务不存在: " + id, null));
            }
            
            Map<String, Object> result = convertToMap(todoTaskOpt.get());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 创建待办任务
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTodoTask(@RequestBody Map<String, Object> requestBody) {
        try {
            // 获取用户ID
            Long userId = null;
            if (requestBody.get("userId") != null) {
                if (requestBody.get("userId") instanceof Integer) {
                    userId = Long.valueOf((Integer) requestBody.get("userId"));
                } else if (requestBody.get("userId") instanceof Long) {
                    userId = (Long) requestBody.get("userId");
                } else {
                    userId = Long.parseLong(requestBody.get("userId").toString());
                }
            }
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户ID不能为空", null));
            }
            
            // 检查用户是否存在
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }
            
            // 创建待办任务
            TodoTask todoTask = new TodoTask();
            todoTask.setUser(userOpt.get());
            
            // 设置内容
            if (requestBody.get("content") == null || requestBody.get("content").toString().isEmpty()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "待办内容不能为空", null));
            }
            todoTask.setContent(requestBody.get("content").toString());
            
            // 设置优先级
            if (requestBody.get("priority") != null) {
                todoTask.setPriority(requestBody.get("priority").toString());
            } else {
                todoTask.setPriority("medium");
            }
            
            // 设置截止日期
            if (requestBody.get("dueDate") != null) {
                todoTask.setDueDate(LocalDate.parse(requestBody.get("dueDate").toString()));
            }
            
            // 设置完成状态
            if (requestBody.get("completed") != null) {
                todoTask.setCompleted(Boolean.parseBoolean(requestBody.get("completed").toString()));
                
                // 如果任务已完成，设置完成时间
                if (todoTask.getCompleted()) {
                    todoTask.setCompleteTime(LocalDateTime.now());
                }
            } else {
                todoTask.setCompleted(false);
            }
            
            // 保存待办任务
            TodoTask savedTodoTask = todoTaskRepository.save(todoTask);
            
            Map<String, Object> result = convertToMap(savedTodoTask);
            
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(new ApiResponse<>(true, "创建待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "创建待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 更新待办任务
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateTodoTask(
            @PathVariable Long id,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 检查待办任务是否存在
            Optional<TodoTask> todoTaskOpt = todoTaskRepository.findById(id);
            if (!todoTaskOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "待办任务不存在: " + id, null));
            }
            
            TodoTask todoTask = todoTaskOpt.get();
            
            // 更新用户信息
            if (requestBody.get("userId") != null) {
                Long userId;
                if (requestBody.get("userId") instanceof Integer) {
                    userId = Long.valueOf((Integer) requestBody.get("userId"));
                } else if (requestBody.get("userId") instanceof Long) {
                    userId = (Long) requestBody.get("userId");
                } else {
                    userId = Long.parseLong(requestBody.get("userId").toString());
                }
                
                // 检查用户是否存在
                Optional<User> userOpt = userRepository.findById(userId);
                if (!userOpt.isPresent()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
                }
                
                todoTask.setUser(userOpt.get());
            }
            
            // 更新内容
            if (requestBody.get("content") != null) {
                if (requestBody.get("content").toString().isEmpty()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "待办内容不能为空", null));
                }
                todoTask.setContent(requestBody.get("content").toString());
            }
            
            // 更新优先级
            if (requestBody.get("priority") != null) {
                todoTask.setPriority(requestBody.get("priority").toString());
            }
            
            // 更新截止日期
            if (requestBody.get("dueDate") != null) {
                todoTask.setDueDate(LocalDate.parse(requestBody.get("dueDate").toString()));
            }
            
            // 更新完成状态
            if (requestBody.get("completed") != null) {
                boolean newCompletedStatus = Boolean.parseBoolean(requestBody.get("completed").toString());
                
                // 如果任务从未完成变为已完成，设置完成时间
                if (!todoTask.getCompleted() && newCompletedStatus) {
                    todoTask.setCompleteTime(LocalDateTime.now());
                } else if (todoTask.getCompleted() && !newCompletedStatus) {
                    // 如果任务从已完成变为未完成，清除完成时间
                    todoTask.setCompleteTime(null);
                }
                
                todoTask.setCompleted(newCompletedStatus);
            }
            
            // 保存更新后的待办任务
            TodoTask updatedTodoTask = todoTaskRepository.save(todoTask);
            
            Map<String, Object> result = convertToMap(updatedTodoTask);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "更新待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 删除待办任务
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteTodoTask(@PathVariable Long id) {
        try {
            // 检查待办任务是否存在
            if (!todoTaskRepository.existsById(id)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "待办任务不存在: " + id, null));
            }
            
            // 删除待办任务
            todoTaskRepository.deleteById(id);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "删除待办任务成功", null));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "删除待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 获取用户的未完成待办任务
     */
    @GetMapping("/user/{userId}/pending")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getPendingTodoTasks(@PathVariable Long userId) {
        try {
            // 检查用户是否存在
            if (!userRepository.existsById(userId)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }
            
            // 获取未完成的待办任务
            List<TodoTask> pendingTasks = todoTaskRepository.findByUserIdAndCompleted(userId, false);
            
            // 转换为Map格式
            List<Map<String, Object>> result = pendingTasks.stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户未完成待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户未完成待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 获取用户今天到期的未完成待办任务
     */
    @GetMapping("/user/{userId}/today")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTodayTodoTasks(@PathVariable Long userId) {
        try {
            // 检查用户是否存在
            if (!userRepository.existsById(userId)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }
            
            // 获取今天及以前到期的未完成待办任务
            List<TodoTask> todayTasks = todoTaskRepository.findByUserIdAndCompletedFalseAndDueDateLessThanEqual(
                    userId, LocalDate.now());
            
            // 转换为Map格式
            List<Map<String, Object>> result = todayTasks.stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户今天到期的未完成待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户今天到期的未完成待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 获取用户下周到期的未完成待办任务
     */
    @GetMapping("/user/{userId}/next-week")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getNextWeekTodoTasks(@PathVariable Long userId) {
        try {
            // 检查用户是否存在
            if (!userRepository.existsById(userId)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }
            
            // 获取下周到期的未完成待办任务
            LocalDate today = LocalDate.now();
            LocalDate nextWeek = today.plusDays(7);
            
            List<TodoTask> nextWeekTasks = todoTaskRepository.findByUserIdAndCompletedFalseAndDueDateBetween(
                    userId, today, nextWeek);
            
            // 转换为Map格式
            List<Map<String, Object>> result = nextWeekTasks.stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户下周到期的未完成待办任务成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户下周到期的未完成待办任务失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 标记待办任务为已完成
     */
    @PutMapping("/{id}/complete")
    public ResponseEntity<ApiResponse<Map<String, Object>>> completeTodoTask(@PathVariable Long id) {
        try {
            // 检查待办任务是否存在
            Optional<TodoTask> todoTaskOpt = todoTaskRepository.findById(id);
            if (!todoTaskOpt.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "待办任务不存在: " + id, null));
            }
            
            TodoTask todoTask = todoTaskOpt.get();
            
            // 标记为已完成
            todoTask.setCompleted(true);
            todoTask.setCompleteTime(LocalDateTime.now());
            
            // 保存更新后的待办任务
            TodoTask updatedTodoTask = todoTaskRepository.save(todoTask);
            
            Map<String, Object> result = convertToMap(updatedTodoTask);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "标记待办任务为已完成成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "标记待办任务为已完成失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 将TodoTask转换为Map
     */
    private Map<String, Object> convertToMap(TodoTask todoTask) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", todoTask.getId());
        map.put("userId", todoTask.getUser() != null ? todoTask.getUser().getId() : null);
        map.put("username", todoTask.getUser() != null ? todoTask.getUser().getUsername() : null);
        map.put("content", todoTask.getContent());
        map.put("priority", todoTask.getPriority());
        map.put("dueDate", todoTask.getDueDate());
        map.put("completed", todoTask.getCompleted());
        map.put("completeTime", todoTask.getCompleteTime());
        map.put("createdAt", todoTask.getCreatedAt());
        map.put("updatedAt", todoTask.getUpdatedAt());
        return map;
    }
} 